const express = require("express");
const app = express();

var http = require("http");

/* 导入两个对象 */
/* 1、导入 */
var xml2js = require('xml2js');
/* 2、创建xml->js对象 */
var parser = new xml2js.Parser({
    explicitArray: false
});
/* 3、创建 js->xml对象 */
var builder = new xml2js.Builder({
    rootName: "xml",
    cdata: true,
    headless: true
})


app.get('/', (req, res) => {
    //console.log(req.query);
    res.send(req.query.echostr);
})
app.post('/', (req, res) => {
    /* 获取数据  数据流事件监听 */
    /* 获取数据  数据流事件监听 */
    /*  var bufferList=null;
     req.on("data",function(buffer){
        bufferList+=buffer
     })
     req.on("end",function(){
         console.log(bufferList)
     }) */
    var bufferList = [];
    req.on("data", function (buffer) {
        bufferList.push(buffer);
    })
    req.on("end", function () {
        var result = Buffer.concat(bufferList);
        /* 获取微信服务器发来的消息数据  使用xml2js转换成js对象 */
        parser.parseString(result.toString(), (err, msgObj) => {
            console.log(msgObj, 88);
            /* 声明一个变量用来保存我们要回复给用户的消息 */
            var msg = '';


            /* 拿到用户消息后，通过请求图灵机器人，获取回复内容，
            将回复内容响应给微信服务器 */
            /* 1、构建请求参数对象 */
            var data = JSON.stringify({
                'key': '4a253b550e634260996205331859805c',
                'info': msgObj.xml.Content,
                'userid': msgObj.xml.FromUserName
            });

            /* 2、构建请求对象 */
            var req = http.request({
                method: "post",
                host: "www.tuling123.com",
                protocol: "http:",
                post: "80",
                path: "/openapi/api",
                headers: {
                    "Content-Type": "application/json",
                    "Content-Length": Buffer.byteLength(data)
                }
            }, function (response) {
                var bufferList_r = [];
                response.on("data", function (buffer) {
                    bufferList_r.push(buffer);
                });
                response.on("end", function () {
                    var result_r = Buffer.concat(bufferList_r);
                    console.log(result_r.toString());
                    /* result就是图灵机器人返回来的消息 */
                    msg = JSON.parse(result_r).text;
                    console.log(msg,5566);
                    
                    var returnMsg = {
                        ToUserName: msgObj.xml.FromUserName, //开发者微信号
                        FromUserName: msgObj.xml.ToUserName, //发送方帐号（一个OpenID）
                        CreateTime: +new Date(),
                        MsgType: 'text',
                        Content: msg,
                    };

                    /* 响应给用户 */
                    res.send(builder.buildObject(returnMsg));
                });
            })

            req.write(data);
        })
    })
})
app.listen('80', () => {
    console.log("http://echo.free.idcfengye.com");
})